const QiniuModule = require("qiniu");
const path = require("path");
const QiNiuConfig = {
  host: "http://rwj1wwfpv.hn-bkt.clouddn.com/",
  buckey: "tarde-admin",
  accessKey: "QpBmhI7yvVLwa8qk1XGWm-wuncMlN60fAnU1lsHn",
  secretKey: "JflRBPLDyPoqVF9E6daF3rziL5ZBsIu18qLo_ZFi",
};
function Qiniu() {
  this.bucket = QiNiuConfig.buckey;
  this.mac = new QiniuModule.auth.digest.Mac(
    QiNiuConfig.accessKey,
    QiNiuConfig.secretKey
  );
  this.putPolicy = new QiniuModule.rs.PutPolicy({ scope: QiNiuConfig.buckey });
  // 获取上传凭证
  this.token = this.putPolicy.uploadToken(this.mac);
  // 初始化配置
  this.config = new QiniuModule.conf.Config();
  // 资源管理对象
  this.BucketManager = new QiniuModule.rs.BucketManager(this.mac, this.config);
}
/**
 * 七牛云-普通文件直传
 * 通过该函数进行文件直传，但不建议大文件直传，请使用分片
 * @param { Object } options *上传参数
 * @param { String } options.file *需要上传的文件绝对路径,不能是网络文件路径
 * @param {String} options.name *文件名称（不包含目录路径）
 * @param { String } [options.fileType] *当前上传的文件类型
 * @param { String } [options.dir] 存放目录路径(选填)
 * @param { Array<String> } [options.type] 限制文件上传的类型数组(选填),默认支持所有文件类型
 * @param { Number } [options.size] 当前上传文件的文件大小(选填)
 * @returns { Promise } 文件上传结果,Promise对象
 */
Qiniu.prototype.upload = function (options = {}) {
  return new Promise((resolve, reject) => {
    let notdirTo = "other";
    let { file, name, dir, type, size } = options;
    let putExtra = new QiniuModule.form_up.PutExtra();
    let formUploader = new QiniuModule.form_up.FormUploader(this.config);
    let token = this.token;
    // 文件名称（包含目录路径）
    let savePath = dir
      ? `${dir}/${name}`
      : notdirTo
      ? `${notdirTo}/${name}`
      : name;
    // 最大文件大小限制
    let file_max_size = null;
    // 最小文件大小限制
    let file_min_size = null;
    // 文件限制判断-类型
    if (Array.isArray(type)) {
      let allowUpload = type.includes(filetype);
      if (!allowUpload) {
        reject({
          code: 302,
          msg: "上传文件类型不支持",
        });
      }
    }
    // 文件大小限制
    if (
      (file_max_size && file_max_size < size) ||
      (file_min_size && file_min_size > size)
    ) {
      reject({
        code: 302,
        msg: "文件大小超出限制",
      });
      return;
    }
    formUploader.putFile(token, savePath, file, putExtra, (err, data, res) => {
      if (err) {
        console.log(err);
        reject({
          code: 500,
          msg: "文件上传失败",
        });
        return;
      }
      if (res.statusCode == 200) {
        let host = QiNiuConfig.host;
        let filePath = path.join(host, data.key);
        resolve({
          code: 0,
          msg: "上传成功",
          src: filePath,
          hash: data.hash,
          key: data.key,
        });
      } else {
        reject({
          code: res.statusCode,
          msg: "文件上传失败",
        });
      }
    });
  });
};

/**
 * 七牛云-获取空间内文件信息
 * @param {String} key 文件key
 * @returns {Promise}
 */
Qiniu.prototype.fileinfo = function (key) {
  return new Promise((resolve, reject) => {
    let bucket = this.bucket;
    this.bucketManager.stat(bucket, key, (err, respBody, respInfo) => {
      if (err) {
        reject({
          code: err.code,
          msg: "文件获取失败",
        });
      } else {
        if (respInfo.statusCode == 200) {
          let { hash, fszie, mimeType, putTime, type } = respBody;
          resolve({
            code: 0,
            msg: "获取成功",
            fileinfo: {
              hash,
              fszie,
              mimeType,
              putTime,
              type,
            },
          });
        } else {
          reject({
            code: respInfo.statusCode,
            msg: "文件获取失败",
          });
        }
      }
    });
  });
};
/**
 * 七牛云-分片上传
 * @param {String} key 文件key
 * @returns {Promise}
 */
Qiniu.prototype.chunkUpload = function () {};
module.exports = new Qiniu();